<template>
  <div>
    <PageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
      <template #footer>
        <a-space v-if="authData.state === 1">
          <a-button type="outline" status="danger" @click="cancel"
            >取消</a-button
          >
          <a-button type="primary" status="success" @click="TaskRelease">
            <template #icon><icon-storage /></template>
            任务下达</a-button
          >
        </a-space>
      </template>
      <div>
        <h1 class="title">供应商现场验厂认证流程 </h1>
        <div v-if="authData?.state === 4 || authData.state === 5">
          <div class="title-item">
            <span style="padding-left: 40px">样品认证结果</span>
          </div>
          <div style="margin-top: 10px; margin-left: 60px">
            <a-space :size="30" direction="vertical" fill>
              <div>
                是否通过认证：
                <a-radio-group
                  :default-value="authData.state === 4 ? 1 : 2"
                  disabled
                >
                  <a-radio :value="1">
                    <template #radio="{ checked }">
                      <div
                        align="start"
                        class="custom-radio-card"
                        :class="{ 'custom-radio-card-checked': checked }"
                      >
                        <div className="custom-radio-card-shade">
                          <div className="custom-radio-card-masky">
                            <icon-check
                              className="custom-radio-card-mask-dot"
                            />
                          </div>
                        </div>
                        <div className="custom-radio-card-shadey">
                          <a-typography-text type="secondary">
                            通过
                          </a-typography-text>
                        </div>
                      </div>
                    </template>
                  </a-radio>
                  <a-radio :value="2">
                    <template #radio="{ checked }">
                      <div
                        align="start"
                        class="custom-radio-card"
                        :class="{ 'custom-radio-card-checked': checked }"
                        ><div className="custom-radio-card-shade">
                          <div className="custom-radio-card-maskn">
                            <icon-check
                              className="custom-radio-card-mask-dot"
                            />
                          </div>
                        </div>
                        <div className="custom-radio-card-shaden">
                          <a-typography-text type="secondary">
                            不通过
                          </a-typography-text>
                        </div>
                      </div>
                    </template>
                  </a-radio>
                </a-radio-group>
              </div>
              <div>
                <a-space :size="20" direction="vertical" fill>
                  <div> 认证意见： </div>
                  <a-textarea
                    v-model="authData.authPoint"
                    placeholder="请输入意见"
                    allow-clear
                  />
                </a-space>
              </div>
            </a-space>
          </div>
        </div>

        <div
          v-if="authData.state === 4 || authData.state === 5"
          style="margin-top: 30px"
        >
          <div class="title-item">
            <span style="padding-left: 40px">现场验厂报告</span>
          </div>
          <div></div>
        </div>

        <div class="title-item" style="margin-top: 30px">
          <span style="padding-left: 40px">认证任务</span>
        </div>
        <div class="info-item">
          <div style="width: 100%; display: flex; margin: 20px 50px">
            <a-space>
              <div
                style="
                  width: 4px;
                  height: 15px;
                  background-color: rgba(61, 126, 255, 1);
                  border: none;
                  border-radius: 2px;
                "
              >
              </div>
              <div>基本信息</div>
            </a-space>
          </div>
          <div style="width: 100%; display: flex; justify-content: center"
            ><a-form style="width: 60%" :model="formlist" auto-label-width>
              <a-row :gutter="24" justify="space-between">
                <a-col :span="11">
                  <a-form-item label="认证单号："
                    ><a-input
                      v-model="authData.number"
                      :disabled="authData.state !== 1"
                  /></a-form-item>
                </a-col>
                <a-col :span="11">
                  <a-form-item label="供应商编号："
                    ><a-input
                      v-model="formlist.list.number"
                      disabled
                      allow-clear
                  /></a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="24" justify="space-between">
                <a-col :span="11">
                  <a-form-item label="供应商名称："
                    ><a-input v-model="formlist.list.name" disabled allow-clear
                  /></a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="24" justify="space-between">
                <a-col :span="11">
                  <a-form-item label="任务下达时间：">
                    <a-date-picker v-model="authData.taskReleasTime" disabled
                  /></a-form-item>
                </a-col>
                <a-col :span="11">
                  <a-form-item label="下单人：">
                    <a-input
                      placeholder=""
                      allow-clear
                      v-model="Order.name"
                      disabled
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <!-- 执行信息 -->
          <div v-if="authData.state != 1">
            <div style="width: 100%; display: flex; margin: 20px 50px">
              <a-space>
                <div
                  style="
                    width: 4px;
                    height: 15px;
                    background-color: rgba(61, 126, 255, 1);
                    border: none;
                    border-radius: 2px;
                  "
                >
                </div>
                <div>执行信息</div>
              </a-space>
            </div>
            <div style="width: 100%; display: flex; justify-content: center"
              ><a-form style="width: 60%" :model="authData" auto-label-width>
                <a-row :gutter="24" justify="space-between">
                  <a-col :span="12">
                    <a-form-item label="验厂负责人："
                      ><a-input
                        v-model="authData.headManName"
                        :disabled="authData.state !== 1"
                        allow-clear
                    /></a-form-item>
                  </a-col>
                  <a-col :span="12">
                    <a-form-item label="任务开始时间："
                      ><a-input
                        allow-clear
                        @click="Time"
                        :disabled="authData.state !== 1"
                        v-model="authData.beginTime"
                    /></a-form-item>
                  </a-col>
                </a-row>
                <a-row :gutter="24" justify="space-between">
                  <a-col :span="11">
                    <a-form-item label="任务结束时间："
                      ><a-date-picker :disabled="authData.state !== 1"
                    /></a-form-item>
                  </a-col>
                  <a-col :span="11">
                    <a-form-item label="供应商状态："
                      ><div
                        :class="
                          authData.state === 2
                            ? 'Qualified'
                            : authData.state === 3
                            ? 'Examining'
                            : authData.state === 4
                            ? 'Pass'
                            : 'NoPass'
                        "
                      >
                        <span>
                          {{
                            authData.state === 2
                              ? '待执行'
                              : authData.state === 3
                              ? '执行中'
                              : authData.state === 4
                              ? '通过'
                              : '不通过'
                          }}
                        </span>
                      </div></a-form-item
                    >
                  </a-col>
                </a-row>
              </a-form>
            </div>
          </div>
          <div style="width: 100%; display: flex; margin: 20px 50px">
            <a-space>
              <div
                style="
                  width: 4px;
                  height: 15px;
                  background-color: rgba(61, 126, 255, 1);
                  border: none;
                  border-radius: 2px;
                "
              >
              </div>
              <div>任务执行人</div>
            </a-space>
          </div>
          <div style="width: 70%; margin-left: 20%">
            <a-space :size="30" direction="vertical" fill>
              <!-- <div v-if="authData.state === 1">
              <span>验厂负责人：</span>
              <a-select
                v-model="authData.headMan"
                :style="{ width: '320px' }"
                placeholder="Please select ..."
              >
                <a-option
                  v-for="item in Personne"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.name }}</a-option
                >
              </a-select>
            </div> -->
              <a-form
                v-if="authData.state === 1"
                ref="formRef"
                :model="authData"
                :style="{ width: '600px' }"
                @submit="handleSubmit"
              >
                <a-form-item
                  :rules="[{ required: true, message: '请选择任务负责人' }]"
                  field="headMan"
                  label="任务负责人:"
                  required
                >
                  <a-select
                    v-model="authData.headMan"
                    :style="{ width: '320px' }"
                    placeholder="请选择任务负责人"
                  >
                    <a-option
                      v-for="item in Personne"
                      :key="item.id"
                      :value="item.id"
                      >{{ item.name }}</a-option
                    >
                  </a-select>
                </a-form-item>
              </a-form>
              <TableTurn
                :tableData="getData"
                ref="tableTurnRef"
                :is-show-pagination="false"
              >
                <a-table-column
                  data-index="userName"
                  :width="100"
                  align="center"
                  title="姓名"
                >
                </a-table-column>
                <a-table-column
                  data-index="responsibility"
                  :width="100"
                  align="center"
                  title="负责"
                >
                </a-table-column>
                <a-table-column
                  data-index="description"
                  :width="100"
                  align="center"
                  title="职责"
                >
                </a-table-column>
                <a-table-column
                  align="center"
                  :width="100"
                  fixed="right"
                  title="操作"
                >
                  <template #cell="{ record, rowIndex }">
                    <a-button
                      type="text"
                      status="danger"
                      @click="delMans(record.id, rowIndex)"
                      >删除</a-button
                    >
                  </template>
                </a-table-column>
              </TableTurn>
            </a-space>
            <div>
              <a-button
                :disabled="authData.state !== 1"
                type="text"
                @click="AddMembers"
              >
                <template #icon>
                  <icon-plus />
                </template>
                添加
              </a-button>
            </div>
          </div>

          <div style="width: 100%; margin: 50px 50px">
            <a-space direction="vertical" fill>
              <div> 注意事项： </div>
              <div>
                <a-textarea
                  v-model="authData.description"
                  placeholder="Please enter something"
                  allow-clear
                  :disabled="authData.state > 1"
                />
              </div>
            </a-space>
          </div>
          <div style="width: 100%; margin: 20px 50px">
            <a-space :size="20" direction="vertical" fill>
              <div>验厂所需附件：</div>
              <UploadFile
                ref="FileRef"
                v-model:file-list="fileAll"
                :limit="0"
              ></UploadFile>
              <!-- <div v-for="(element, index) in authData.file" :key="index">
              <a-space direction="vertical" fill>
                <div>
                  <a-button
                    :disabled="authData.state !== 1"
                    type="primary"
                    @click="upload(index)"
                    >上传文件</a-button
                  >
                  <div class="uploadFile">
                    <div>{{ element.name }} </div>
                    <a :href="element.fileAddr" :download="element.name"
                      >下载</a
                    >
                  </div>
                </div>
              </a-space>
            </div>
            <div v-if="authData.state === 1" style="display: flex">
              <div @click="addFile">
                <icon-plus />
                <a-typography-text type="primary">
                  添加附加类型
                </a-typography-text></div
              >
              <div>
                <span style="margin: 2px 50px"
                  >支持pdf、doc、docx、wps文件格式，大小不超过20MB</span
                >
              </div>
            </div> -->
            </a-space>
          </div>

          <div v-if="authData.state === 3">
            <div v-if="ShowResults">
              <div class="title-item">
                <span style="padding-left: 40px">现场验厂认证结果</span>
              </div>
              <div style="width: 95%; margin: 20px 40px">
                <a-space :size="40" direction="vertical" fill>
                  <div
                    ><span>是否通过认证：</span>
                    <a-radio-group @change="authStateData">
                      <a-radio :value="4">
                        <template #radio="{ checked }">
                          <div
                            align="start"
                            class="custom-radio-card"
                            :class="{ 'custom-radio-card-checked': checked }"
                          >
                            <div className="custom-radio-card-shade">
                              <div className="custom-radio-card-masky">
                                <icon-check
                                  className="custom-radio-card-mask-dot"
                                />
                              </div>
                            </div>
                            <div className="custom-radio-card-shadey">
                              <a-typography-text
                                style="margin-left: 30%"
                                type="secondary"
                              >
                                合格
                              </a-typography-text>
                            </div>
                          </div>
                        </template>
                      </a-radio>
                      <a-radio :value="5">
                        <template #radio="{ checked }">
                          <div
                            align="start"
                            class="custom-radio-card"
                            :class="{ 'custom-radio-card-checked': checked }"
                          >
                            <div className="custom-radio-card-shade">
                              <div className="custom-radio-card-maskn">
                                <icon-check
                                  className="custom-radio-card-mask-dot"
                                />
                              </div>
                            </div>
                            <div className="custom-radio-card-shaden">
                              <a-typography-text
                                style="margin-left: 30%"
                                type="secondary"
                              >
                                不合格
                              </a-typography-text>
                            </div>
                          </div>
                        </template>
                      </a-radio>
                    </a-radio-group></div
                  >
                  <div>
                    <a-space direction="vertical" fill>
                      <span>认证意见：</span>
                      <a-textarea
                        v-model="authData.authPoint"
                        placeholder=""
                        allow-clear
                      />
                    </a-space>
                  </div>
                </a-space>
              </div>
            </div>
          </div>

          <addMember
            v-model:visible="modelVisible"
            @addCocMemder="addCocMemder"
          ></addMember>
        </div>
      </div>
    </PageHeader>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, computed, ref, watchEffect } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { getSupplierauth } from '@/api/buy-management/supplier-management/base-setting/index';
  import {
    postSupplierMans,
    getSupplierProduct,
    delSupplierMans,
    putSupplierAuth,
  } from '@/api/buy-management/supplier-management/supplier-certification/index';
  import { GetSupplierPrimaryDetail } from '@/api/buy-management/supplier-management/supplier-primary-list/index';
  import { cloneDeep } from 'lodash';
  import { GetPersonnelinformation } from '@/api/home/System settings/personal-information/index';
  import dayjs from 'dayjs';
  import { openChoiceFile } from '@/utils/file';
  import { FileUpload } from '@/utils/upload';
  // import axios from 'axios';
  // import { getToken } from '@/utils/auth';
  import { number } from 'echarts';
  import addMember from './add-member/index.vue';

  const route = useRoute();
  const router = useRouter();
  const tableTurnRef = ref();
  const title: string = '供应商现场验厂认证';
  const modelVisible = ref(false);
  const uploadFileShow = ref(false);
  const formRef = ref();
  const breadCrumb: string[] = [
    '采购管理',
    '供应商管理',
    '供应商认证项目设置',
    '供应商现场验厂认证',
  ];

  const file = ref({
    name: '',
    file_type: '',
    des: '',
  });

  const ShowResults = ref(false);
  const formlist = reactive({ list: { number: '', name: '' } });
  let authData: any = ref({
    state: null,
    headMan: null,
    file: [],
  });
  const Order = ref(JSON.parse(sessionStorage.getItem('loginInfo') as any));
  const supplierId = ref();

  const getdetailsdata = async () => {
    const res = await GetSupplierPrimaryDetail({
      id: Number(route.query.gys),
    });
    const msg = await getSupplierProduct({
      id: Number(route.query.auth),
    });
    formlist.list = res;
    supplierId.value = Number(route.query.gys);
    authData.value = msg;
    authData.value.taskReleasTime = new Date().toJSON();
    authData.value.headMan = null;
    if (authData.value.authReport.length > 0) {
      ShowResults.value = true;
    }
  };
  getdetailsdata();

  // 获取人员信息
  const Personne = ref();
  const Personnelinformation = async () => {
    const res = await GetPersonnelinformation({ page: 0, size: 9999 });
    Personne.value = res.content.data;
  };
  Personnelinformation();

  // 点击添加成员
  const AddMembers = () => {
    modelVisible.value = true;
  };

  let fileAll = computed({
    get() {
      const newarr = authData.value.file?.map((element: any) => {
        return {
          sourceAddr: element.addr,
          fileUrl: element.fileAddr,
          fileName: element.name,
        };
      });
      return newarr.length > 0 ? newarr : [];
    },
    set(val: any[]) {
      authData.value.file =
        val?.map((element) => {
          return {
            addr: element.sourceAddr,
            name: element.fileName,
            fileAddr: element.fileUrl,
            fileType: 2,
            supplierFileType: 1,
          };
        }) || [];
    },
  });
  const Time = () => {
    let beginTime = new Date().toJSON();
    authData.value.beginTime = dayjs(beginTime).format('YYYY-MM-DD HH:mm:ss');
  };

  // 获取成员表格数据
  const fileData = ref();
  const getData = async () => {
    try {
      const res = await getSupplierProduct({
        id: Number(route.query.auth),
      });
      fileData.value = res.file;
      return Promise.resolve(res.members);
    } catch (err: unknown) {
      console.log(err);
    }
  };
  // 点击确认添加成员
  const addCocMemder = async (formData: any) => {
    await postSupplierMans({
      supplierAuthId: authData.value.id,
      userId: formData.userId,
      responsibility: formData.responsibility,
      description: formData.description,
    });
    tableTurnRef.value.loadData();
  };
  // 取消
  const cancel = () => {
    router.go(-1);
  };
  // 点击删除成员
  const delMans = async (id: number, index: number) => {
    await delSupplierMans({ id });
    tableTurnRef.value.loadData();
  };

  const addFile = () => {
    authData.value.file.push({});
  };

  // 文件上传
  const form = reactive<{ file?: File }>({});
  const upload = async (Uindex: number) => {
    let file = new FormData();
    form.file = await openChoiceFile(
      ['.mp4', '.pdf', '.png', '.txt', '.jpg', '.docx'],
      1024 * 1024 * 10
    );
    file.append('data', form.file);
    const res = (await FileUpload(file)) as any;
    authData.value.file.forEach((item: any, index: number) => {
      if (Uindex === index) {
        item.name = res.data.data.name;
        item.addr = res.data.data.sourceAddr;
        item.fileAddr = res.data.data.addr;
        item.fileType = 2;
        item.supplierFileType = 1;
        uploadFileShow.value = true;
      }
    });
  };

  const StateData = ref();
  const authStateData = (key: any) => {
    StateData.value = key;
  };

  // 任务下达
  const TaskRelease = () => {
    formRef.value.validate(async (res) => {
      if (!res) {
        authData.value.state = 2;
        authData.value.taskReleaser = Order.value.id;
        await putSupplierAuth(authData.value);
        router.go(-1);
      }
    });
  };

  const downloadFile = (res: any) => {
    // 创建一个链接元素
    const link = document.createElement('a');
    link.href = res.fileAddr;

    // 设置下载属性并将其插入到DOM中
    link.download = res.name; // 设置下载的文件名
    document.body.appendChild(link);
    // 触发点击事件以开始下载
    link.click();
    // 下载完成后，移除该链接元素
    document.body.removeChild(link);
  };

  // const GetQuestionnaireExcelTem = (res: any) => {
  //   // const res: Blob = await requredService({
  //   //   url: '/enterprise/form_question/excel/template',
  //   //   method: 'get',
  //   //   baseURL: env.VITE_APP_YUANTAO_URL,
  //   //   loadingTip: '导入中',
  //   //   responseType: 'blob',
  //   // });

  //   const file = new Blob([res.fileAddr], { type: `application/${res.name.split('.')[1]}` });
  //   const changeUrl = window.webkitURL.createObjectURL(file);
  //   let downloadElement: any = document.createElement('a');
  //   downloadElement.download = res.name;
  //   downloadElement.href = changeUrl;
  //   downloadElement.click();
  //   downloadElement = undefined;
  //   window.URL.revokeObjectURL(changeUrl);
  // };
</script>

<style scoped lang="less">
  .basic-item {
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px solid rgba(242, 243, 245, 0.852);
  }

  .title {
    margin-left: 45%;
  }

  .title-item {
    width: 95%;
    height: 60px;
    margin: auto;
    background-color: rgba(245, 247, 250);
    line-height: 60px;
  }

  .info-item {
    width: 100%;
  }
  .state-item {
    width: 95px;
    height: 40px;
    background: inherit;
    background-color: rgba(228, 228, 228, 1);
    border: none;
    border-radius: 100px;
    line-height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: aliceblue;
  }

  .report-item {
    width: 95%;
    height: 60px;
    margin: auto;
    background-color: rgba(245, 247, 250);
    line-height: 60px;
  }

  .custom-radio-card {
    padding: 10px 16px;
    border: 1px solid var(--color-border-2);
    border-radius: 4px;
    width: 150px;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    height: 40px;
    line-height: 40px;
    display: flex;
  }

  .custom-radio-card-masky {
    height: 17px;
    width: 17px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 100%;
    border: 1px solid var(--color-border-2);
    box-sizing: border-box;
    margin-left: 30%;
  }

  .custom-radio-card-maskn {
    height: 17px;
    width: 17px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 100%;
    border: 1px solid var(--color-border-2);
    box-sizing: border-box;
    margin-left: 30%;
  }

  .custom-radio-card-mask-dot {
    width: 8px;
    height: 8px;
    border-radius: 100%;
  }

  .custom-radio-card-title {
    color: var(--color-text-1);
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 8px;
  }
  .custom-radio-card-shade {
    width: 45px;
    height: 38px;
    border-right: 1px solid var(--color-border-2);
    background-color: white;
    box-sizing: border-box;
  }

  .custom-radio-card-shadey {
    width: 105px;
    height: 38px;
    background-color: white;
    box-sizing: border-box;
  }

  .custom-radio-card-shaden {
    width: 105px;
    height: 38px;
    background-color: white;
    box-sizing: border-box;
  }

  .custom-radio-card-checked .custom-radio-card-masky {
    border-color: rgb(49, 194, 124);
  }

  .custom-radio-card-checked .custom-radio-card-maskn {
    border-color: rgb(255, 153, 0);
  }

  .custom-radio-card-checked .custom-radio-card-shadey {
    // background-color: var(--color-primary-light-1);
    // ba-color: rgb(49, 194, 124);
    color: white;
    background-color: rgb(49, 194, 124);
  }
  .custom-radio-card-checked .custom-radio-card-shaden {
    // background-color: var(--color-primary-light-1);
    // ba-color: rgb(49, 194, 124);
    color: white;
    background-color: rgb(255, 153, 0);
  }

  .custom-radio-card:hover .custom-radio-card-title,
  .custom-radio-card-checked .custom-radio-card-title {
    color: rgb(var(--primary-6));
  }

  .custom-radio-card-checked .custom-radio-card-mask-dot {
    background-color: rgb(var(--primary-6));
  }

  .WaitSubmitted {
    // 待下达
    width: 95px;
    height: 40px;
    border-radius: 100px;
    line-height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #c9cdd4;
    color: rgb(255, 255, 255);
    border: none;
  }
  .Examining {
    // 执行中
    width: 95px;
    height: 40px;
    border-radius: 100px;
    line-height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #165dff;
    border: none;
  }
  .Pass {
    // 已通过
    width: 95px;
    height: 40px;
    border-radius: 100px;
    line-height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: rgba(49, 194, 124);
    color: #31c27c;
    border: none;
  }
  .NoPass {
    //不通过
    width: 95px;
    height: 40px;
    border-radius: 100px;
    line-height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f53f3f;
    border: none;
  }
  .Qualified {
    // 待执行
    width: 95px;
    height: 40px;
    border-radius: 100px;
    line-height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255, 247, 232);
    border: none;
    color: #ff9a2e;
  }

  .uploadFile {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    box-sizing: border-box;
    width: 40%;
    padding: 8px 10px 8px 12px;
    overflow: hidden;
    font-size: 14px;
    background-color: var(--color-fill-1);
    border-radius: var(--border-radius-small);
    transition: background-color 0.1s cubic-bezier(0, 0, 1, 1);
    margin-top: 10px;
  }

  :deep(.arco-input-wrapper),
  :deep(.arco-input[disabled]) {
    -webkit-text-fill-color: black;
  }
</style>
